﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MyHealthByDesignWebsite.Models;
using System.Net.Mail;

namespace MyHealthByDesignWebsite.Controllers
{

    //Description:  Use to get and set Health Measure model data using the related view
    //Created:  Oct 2011
    //Programmer:  Jon Barnard
    //Modifications: Kinosha Wimalaratne (Nov-2011 User registration)

    public class AccountController : Controller
    {
        //
        // GET: /Account/LogOn
        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn
        //pre-condition: 
        //post-condition: if user is found, user is logged in.
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (Membership.ValidateUser(model.UserName, model.Password))
                    {
                        FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                        if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1
                            && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//")
                            && !returnUrl.StartsWith("/\\"))
                        {
                 
                            return Redirect(returnUrl);
                        }
                        else
                        {
                        
                            FullDataSetDataContext db = new FullDataSetDataContext();
                            User usr = db.Users.Single(u => u.U_email == model.UserName);
                            //add userid to cookie
                            HttpCookie userIDCookie = new HttpCookie("UserID", Convert.ToString(usr.U_userID));
                            userIDCookie.Expires = DateTime.Now.AddYears(1);
                            Response.Cookies.Add(userIDCookie);
                            
                            //if user has not yet filled out initial survey(s)
                            if(Roles.IsUserInRole(User.Identity.Name, "HealthCheckComplete"))
                                return RedirectToAction("MyHealth", "Home"); 
                            else
                                return RedirectToAction("Index", "MyHealthMeasurements");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError
                            ("", "The user name or password provided is incorrect.");
                    }
                }
                catch (Exception e)
                {
                    ModelState.AddModelError
                        ("", "Database Error. Database could not be contacted");
                }
            }//end if model state is valid

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff
        //pre-condition: User is logged in.
        //post-condition: User is logged out.
        public ActionResult LogOff(FormCollection result)
        {
            //remove user ID from cookie
            HttpCookie userCookie = Request.Cookies["UserID"];
            userCookie.Expires = DateTime.Now.AddYears(-10);
            userCookie.Value = "";
            
            FormsAuthentication.SignOut();               
            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register
        //pre-condition: 
        //post-condition: display state list
        public ActionResult Register()
        {
            ViewData["StateList"] = new SelectList(new[] { "", "AL","AK","AZ","AR","CA","CO","CT","DC","DE","FL","GA","HI","IA",
                "ID","IL","IN","KS","KY","LA","MA","MD","ME","MI","MN","MO","MS","MT","NC","ND","NE","NH","NJ",
                "NM","NV","NY","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VA","VT","WA","WI","WV","WY" });

            var db = new FullDataSetDataContext();
            IEnumerable<SelectListItem> item = db.Ethnicities
              .Select(c => new SelectListItem
              {
                  Value = c.E_ethnicityID,
                  Text = c.E_desc
                });
            ViewData["Ethnicity"] = item;
            return View();
        }

        //
        // POST: /Account/Register
        //pre-condition: 
        //post-condition: If user enters all required data, User is created in database and User is logged in.
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
//TESTING-delete username before re-adding
//FullDataSetDataContext ddb = new FullDataSetDataContext();
//User us = ddb.Users.Single(u => u.U_email == model.UserName);
//ddb.Users.DeleteOnSubmit(us);
//ddb.SubmitChanges();
//Membership.DeleteUser(model.UserName, true);

                Membership.CreateUser(model.UserName, model.Password, null, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);

                    //create new user
                    FullDataSetDataContext db = new FullDataSetDataContext();
                    User usr = new User() { U_fname = model.FirstName, U_lname = model.LastName, U_email = model.UserName };

                    usr.U_address = model.Address;
                    usr.U_city = model.City;
                    usr.U_state = model.State;
                    usr.U_zipcode = model.Zipcode;
                    usr.U_mobilephone = model.MobilePhone;
                    usr.U_DOB = Convert.ToDateTime(model.DOB);
                    //usr.U_userValidity= ;
                    
                    // add the asp user id to the users table
                    aspnet_User aspUser = db.aspnet_Users.SingleOrDefault
                        (u => u.UserName == model.UserName);
                    usr.U_loginID = aspUser.UserId;   
                    usr.U_sex = model.Sex[0];

                    //Save Order
                    db.Users.InsertOnSubmit(usr);
                    db.SubmitChanges();

                    //add userid to cookie
                    HttpCookie userIDCookie = new HttpCookie("UserID", Convert.ToString(usr.U_userID));
                    userIDCookie.Expires = DateTime.Now.AddDays(1);
                    Response.Cookies.Add(userIDCookie);

                    //redirect to initial survey 
                    return RedirectToAction("Index", "MyHealthMeasurements");
                }
                else if (createStatus == MembershipCreateStatus.DuplicateUserName)
                {
                    ModelState.AddModelError("Username already exists in database!", ErrorCodeToString(createStatus));
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword
        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword
        //pre-condition: User is logged in.
        //post-condition: password is updated in database.
        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser
                        (User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword
                        (model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess
        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        //
        // GET: /Account/PasswordEmailed
        [Authorize]
        public ActionResult PasswordEmailed()
        {
            return View();
        }

        [Authorize]
        public ActionResult EmailPassword()
        {
            return View();
        }

        [Authorize]
        public ActionResult EmailPassword(LogOnModel model)
        {
            return View();
        }

        // GET: /Account/ForgotPassword
        public ActionResult ForgotPassword()
        {
            return View();
        }

        //
        // POST: /Account/ForgotPassword
        [Authorize]
        [HttpPost]
        public ActionResult ForgotPassword(LogOnModel model)
        {
            if (ModelState.IsValid)
            {

                bool emailAddressFound;
                try
                {
                    //verify email address exists in database
                    FullDataSetDataContext db = new FullDataSetDataContext();
                    emailAddressFound = db.Users.Any(u => u.U_email == model.UserName);
                    //"select count from users where emailAddress = model.EmailAddress"

                    emailAddressFound = true;
                }
                catch (Exception) {
                    emailAddressFound = false;
                }

                if (emailAddressFound)
                {
                    try{
                        //try to retrieve password
                        MembershipUser u = Membership.GetUser
                        (model.UserName, true /* userIsOnline */);

                        String strPassword = "your password is:";
                        strPassword += u.GetPassword();
                        //send email with reminder password
                        MailMessage mailObj = new MailMessage("jbarnard@pio.carrollu.edu", model.UserName, "Forgotten Paswword Reminder", strPassword);
                        SmtpClient SMTPServer = new SmtpClient("localhost");

                        SMTPServer.Send(mailObj);
                         
                        //email successfully sent
                        return RedirectToAction("PasswordEmailed");
                    }
                    catch (Exception ex) {
                        ModelState.AddModelError
                            ("", "Unable to send email to the specified email address.");
                    }
                }
                else
                {
                    ModelState.AddModelError
                        ("", "The email Address was not found in our system.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
